package com.hzit.hzb.core.controller.api;


import cn.hutool.http.server.HttpServerResponse;
import com.hzit.common.result.R;
import com.hzit.common.result.ResponseEnum;
import com.hzit.hzb.base.util.JwtUtils;
import com.hzit.hzb.core.pojo.vo.LoginVO;
import com.hzit.hzb.core.pojo.vo.RegisterVO;
import com.hzit.hzb.core.pojo.vo.UserIndexVO;
import com.hzit.hzb.core.pojo.vo.UserInfoVO;
import com.hzit.hzb.core.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 用户基本信息 前端控制器
 * </p>
 *
 * @author hbxfwf
 * @since 2024-08-27
 */
@RestController
@RequestMapping("/api/core/userInfo")
@Api(tags = "用户信息接口")
public class UserInfoController {

	@Autowired
	private UserInfoService userInfoService;

	@GetMapping("/list")
	@ApiOperation("用户信息列表")
	public R list(){
		return R.ok().data("list",userInfoService.list());
	}

	// 用户注册
	@PostMapping("/register")
	@ApiOperation("用户注册")
	public R register(
				@ApiParam(value="注册信息",required = true)
				@RequestBody RegisterVO vo){
		userInfoService.register(vo);
		return R.ok().message("注册成功！");
	}

	// 用户登录
	@PostMapping("/login")
	@ApiOperation("用户登录")
	public R login(@RequestBody @ApiParam(value="登录用户信息",required = true) LoginVO vo,
	               HttpServletRequest request){
		String ip = request.getRemoteAddr();
		// HttpServletResponse response = null;
		// Cookie cookie = new Cookie("a","b");
		// response.addCookie(cookie);
		UserInfoVO userInfoVO = userInfoService.login(vo,ip);
		//返回给前端
		return R.ok().data("userInfo",userInfoVO);
	}

	// 令牌校验
	@ApiOperation("校验令牌")
	@GetMapping("/checkToken")
	public R checkToken(@RequestHeader("token") String token){
		boolean result = JwtUtils.checkToken(token);
		if(result){
			return R.ok();
		}else{
			return R.setResult(ResponseEnum.LOGIN_AUTH_ERROR);
		}
	}

	// 校验手机号是否在userInfo表中存在
	@ApiOperation("校验手机号是否存在")
	@GetMapping("/check/{mobile}")
	public R checkMobile(@PathVariable("mobile")
						 @ApiParam(value="手机号",required = true)
			             String mobile){
		boolean isExist = userInfoService.checkMobile(mobile);
		return R.ok().data("isExist",isExist);
	}

	/**
	 * 根据登录id获取当前登录用户信息
	 * @param token
	 * @return
	 */
	@GetMapping("/auth/getIndexUserInfo")
	public R getIndexUserInfo(@RequestHeader("token") String token){
		// 1. 得取用户id
		Long userId = JwtUtils.getUserId(token);
		UserIndexVO vo = userInfoService.getIndexUserInfo(userId);
		return R.ok().data("userIndexVO",vo);
	}
}

